﻿using System.Collections.Generic;
using SolidDemo.Business.Interfaces;

namespace SolidDemo.Business.Helpers
{
    public class DataHelper : IDataHelper
    {
        // skipProperties will only be required for primary key IDs or if the destination object contains a property of the same name as in the source object but with no setter. jb
        // Handles mapping of StringDropDownModel.Value to string and vice-versa. jb
        public void MapProperties(object sourceObject, object destinationObject, List<string> skipProperties = null)
        {
            var sourceType = sourceObject.GetType();
            var sourceProperties = sourceType.GetProperties();

            foreach (var sourceProperty in sourceProperties)
            {
                var name = sourceProperty.Name;
                if (skipProperties != null && skipProperties.Contains(name)) continue;

                object value;
                if (sourceProperty.PropertyType.Name == "StringDropDownModel")
                {
                    var ddModel = sourceProperty.GetValue(sourceObject);
                    var ddValue = ddModel.GetType().GetProperty("Value");
                    value = ddValue.GetValue(ddModel);
                }
                else
                {
                    value = sourceProperty.GetValue(sourceObject);
                }

                var propertyInfo = destinationObject.GetType().GetProperty(name);

                if (propertyInfo == null || propertyInfo.SetMethod == null) continue;

                if (propertyInfo.PropertyType.Name == "StringDropDownModel")
                {
                    var ddModel = propertyInfo.GetValue(destinationObject);
                    var ddValue = ddModel.GetType().GetProperty("Value");
                    ddValue.SetValue(ddModel, value);
                }
                else
                {
                    propertyInfo.SetValue(destinationObject, value);
                }
            }
        }
    }
}
